package com.nutiteq.utils;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;

import com.nutiteq.BasicMapComponent;
import com.nutiteq.MapComponent;
import com.nutiteq.MapItem;

public class LogForm extends Form implements CommandListener {
  public static final Command SHOW_LOG = new Command("Show log", Command.ITEM, 0);

  private final Command back;
  private final Command update;

  private final MapComponent mapComponent;

  private final Displayable backTo;

  private final MIDlet midlet;

  private final MapItem mapItem;

  private final BasicMapComponent basicMapComponent;

  public LogForm(final MapItem display, final MIDlet midlet, final Displayable backTo) {
    this(null, display, null, midlet, backTo);
  }

  public LogForm(final MapComponent display, final MIDlet midlet, final Displayable backTo) {
    this(display, null, null, midlet, backTo);
  }

  private LogForm(final MapComponent component, final MapItem item,
      final BasicMapComponent basicMapComponent, final MIDlet midlet, final Displayable backTo) {
    super("Library log");
    this.mapComponent = component;
    this.mapItem = item;
    this.basicMapComponent = basicMapComponent;
    this.midlet = midlet;
    this.backTo = backTo;
    append(getLog());

    back = new Command("Back", Command.BACK, 0);
    update = new Command("Update", Command.ITEM, 0);

    addCommand(back);
    addCommand(update);

    setCommandListener(this);
  }

  public LogForm(final BasicMapComponent basicMapComponent, final MIDlet instance,
      final Displayable backTo) {
    this(null, null, basicMapComponent, instance, backTo);
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == update) {
      deleteAll();
      append(getLog());
    } else if (cmd == back) {
      Display.getDisplay(midlet).setCurrent(backTo);
    }
  }

  private String getLog() {
    if (mapComponent != null) {
      return mapComponent.getLibraryLog();
    }

    if (mapItem != null) {
      return mapItem.getLibraryLog();
    }

    return basicMapComponent.getLibraryLog();
  }
}
